/**
 * 与一些特殊的合约交互时（比如代理合约）需要利用它编码calldata进行交互
 */
import {ethers} from "ethers"
const ALCHEMY_MAINNET_URL = 'https://eth-sepolia.public.blastapi.io';

const provider = new ethers.JsonRpcProvider(ALCHEMY_MAINNET_URL);

// 利用助记词和provider创建钱包
const wallet = ethers.Wallet.fromPhrase('magnet genuine custom runway vessel misery monkey kite chat diary habit decide', provider)
const walletAddress = await wallet.getAddress()
console.log(walletAddress)

// WETH abi
const abiWETH = [
    "function balanceOf(address) public view returns(uint)",
    "function deposit() public payable",
    "function transfer(address, uint) public returns (bool)",
    "function withdraw(uint) public",
];
// WETH合约地址（sepolia 测试网）
const addressWETH = '0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9' // WETH Contract

// 创建可写合约对象
const contractWETH = new ethers.Contract(addressWETH, abiWETH, wallet)

// balanceOf calldata
const callDataBalanceOf = contractWETH.interface.encodeFunctionData("balanceOf", [walletAddress])
console.log(`balnaceOf编码结果:${callDataBalanceOf}`)

// 构建call 参数
const param1 = {
    to: addressWETH,
    data: callDataBalanceOf
}

// 发起交易，可读操作（view/pure）可以用 provider.call(tx)
const balanceWETH = await provider.call(param1)
console.log(`存款前WETH持仓: ${ethers.formatEther(balanceWETH)}`)

const callDataDeposit = contractWETH.interface.encodeFunctionData("deposit")
// 构建参数
const param2 = {
    to: addressWETH, 
    data: callDataDeposit,
    value: ethers.parseEther("0.001")
}
// 发起交易，写入操作需要 wallet.sendTransaction(tx)
const tx = await wallet.sendTransaction(param2)
await tx.wait()
const balanceWETH_deposit = await contractWETH.balanceOf(walletAddress)
console.log(`存款后WETH持仓: ${ethers.formatEther(balanceWETH_deposit)}`)
